package com.mtoolkit.jdbc.handler;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

/**
 * Object array list result set call back handler.
 * 
 * @author 	<a href="mailto:xishizhang@gmail.com">ZhangShixi</a>
 * @version 1.0, 12/8/2011
 * @since 	JDK1.5
 */
public class ArrayListResultSetHandler implements ResultSetHandler<List<Object[]>> {

	/**
     * Handles the result set and return object array list result.
     * 
     * @param  rs result set.
     * 
     * @return object array list result.
     * 
     * @throws SQLException if a SQL error occurs whiling handle result set.
     */ 
	@Override
	public List<Object[]> handle(ResultSet rs) throws SQLException {
		List<Object[]> result = new LinkedList<Object[]>();
		
		while(rs.next()) {
			result.add(doHandleRow(rs));
		}
		
		return result;
	}
	
	/**
	 * Handle current result set row.
	 * 
	 * @param  rs result set.
	 * 
	 * @return row object array.
	 *  
	 * @throws SQLException if a SQL error occurs whiling handle result set.
	 */
	private Object[] doHandleRow(ResultSet rs) throws SQLException {
		int columnCount = rs.getMetaData().getColumnCount();
		Object[] result = new Object[columnCount];
		
		for (int i = 0; i < columnCount; i++) {
			result[i] = rs.getObject(i + 1);
		}
		
		return result;
	}
	
}

